package com.loong.nnm.impl;

import com.alibaba.fastjson.JSONObject;
import com.loong.nnm.entity.alarm.TcaParameter;
import com.loong.nnm.entity.netconf.NetconfBuilderParameters;
import com.loong.nnm.services.NetconfToolServices;
import com.loong.nnm.utils.*;
import net.juniper.netconf.XML;
import net.juniper.netconf.XMLBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.xml.parsers.ParserConfigurationException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service("NetconfToolServices")
public class NetconfToolImpl implements NetconfToolServices {

//    @Resource
    private NetconfProtocolUtils netconfProtocolUtils = new NetconfProtocolUtils();
    XML send = null;

    private static final List<NetconfBuilderParameters> builderParameters = new ArrayList<>();

    private XMLBuilder instanceXMLBuilder() {
        try {
            return new XMLBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void printStr(Object object) {
        System.out.println("-----------------------------------------------------------------------");
        System.out.println(object);
        System.out.println("-----------------------------------------------------------------------");

    }

    @Override
    public int createConnection(NetconfBuilderParameters parameters) {
        builderParameters.add(parameters);
        return netconfProtocolUtils.setUp(parameters);
    }

    @Override
    public boolean getConnectionStatus(String node) {
        return netconfProtocolUtils.isConnected(getExistingConnection(node).getHost());
    }

    @Override
    public String keepalive(String node) {
        send = netconfProtocolUtils.send("<get>\n" +
                "<filter type=\"subtree\">\n" +
                "</filter>\n" +
                "</get>");
        assert send != null;
        return send.toString();
    }

    @Override
    public void close(String node) {
        netconfProtocolUtils.close(node);
    }

    @Override
    public void reboot(String node) {
        netconfProtocolUtils.reboot(node);
    }

    public void reconnection(String node) {
        for (NetconfBuilderParameters builderParameter : builderParameters) {
            if (builderParameter.getHost().equals(node)) {
                netconfProtocolUtils.setUp(builderParameter);
                return;
            }
        }
    }

    public static List<NetconfBuilderParameters> getBuilderParameters() {
        return builderParameters;
    }

    public boolean isExistingConnection(String node) {
        for (NetconfBuilderParameters builderParameter : builderParameters) {
            if (builderParameter.getId().equals(node)) return true;
        }
        return false;
    }

    public NetconfBuilderParameters getExistingConnection(String node) {
        for (NetconfBuilderParameters builderParameter : builderParameters) {
            if (builderParameter.getId().equals(node)) return builderParameter;
            if (builderParameter.getHost().equals(node)) return builderParameter;
        }
        return null;
    }

    public String send(String node,String content){
        NetconfBuilderParameters existingConnection = getExistingConnection(node);
        if (!getConnectionStatus(node))
            netconfProtocolUtils.setUp(existingConnection);
        return netconfProtocolUtils.send(content).toString();
    }

    /**
     * 发送get请求
     *
     * @param node    网元名称
     * @param content 报文
     * @return 响应的json字符串
     */
    @Override
    public String get(String node, String content) {
        NetconfBuilderParameters existingConnection = getExistingConnection(node);
        printStr(existingConnection);
        if (!getConnectionStatus(node))
            netconfProtocolUtils.setUp(existingConnection);
        String getStr = null;
        XML response = netconfProtocolUtils.send(content);
        try {
            JSONObject object = XMLToJsonUtils.xmlToJson(response.toString());
            JSONObject reply = object.getJSONObject("rpc-reply");
            getStr = PrettyJSON.pretty(reply.toString());
            if(reply.containsKey("data")){
                JSONObject data = reply.getJSONObject("data");
                getStr = PrettyJSON.pretty(data.toString());
            }
            System.out.println(getStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return getStr;
    }

    @Override
    public String get(String node, XML xml) {
        return get(node, xml.toString());
    }

    @Override
    public String put(String node, String content) {
        return null;
    }

    @Override
    public String put(String node, XML content) {
        return null;
    }

    @Override
    public String post(String node, String content) {
        return null;
    }

    @Override
    public String post(String node, XML content) {
        return null;
    }

    @Override
    public String delete(String node, XML content) {
        return null;
    }

    @Override
    public String createSubscription(String node) {
        if (!getConnectionStatus(node))
            netconfProtocolUtils.setUp(getExistingConnection(node));
        String message = "<create-subscription xmlns=\"urn:ietf:params:xml:ns:netconf:notification:1.0\">\n" +
                " <stream>NETCONF</stream>\n" +
                " </create-subscription></rpc>";
        String msg = "<create-subscription xmlns=\"urn:ietf:params:xml:ns:netconf:notification:1.0\"/>";
        return netconfProtocolUtils.send(msg).toString();
    }


    /**
     * 测试读取大容量的json文件
     * @return
     */
    public String getJson() {
        String node = "test1";
        LoadJSONFile loadJSONFile = new LoadJSONFile();
        JSONObject obj = loadJSONFile.getLoadJson(node);
        return obj.toString();
    }



    public void setNtpServers() {

        XML me = Objects.requireNonNull(instanceXMLBuilder()).createNewConfig("me");
        me.setAttribute("xmlns", "\"urn:ccsa:yang:acc-devm");
        XML append = me.append("ntp-servers");


    }

    public String setSend() {


        return netconfProtocolUtils.send(" <edit-config>\n" +
                "    <target>\n" +
                "      <running/>\n" +
                "    </target>\n" +
                "    <config>\n" +
                "      <me xmlns=\"urn:ccsa:yang:acc-devm\">\n" +
                "        <ntp-servers>\n" +
                "          <ntp-server>\n" +
                "            <name>ntp_2</name>\n" +
                "            <ip-address>192.186.12.1</ip-address>\n" +
                "            <port>100</port>\n" +
                "            <ntp-version>0.0.1</ntp-version>\n" +
                "          </ntp-server>\n" +
                "        </ntp-servers>\n" +
                "      </me>\n" +
                "    </config>\n" +
                "  </edit-config>").toString();

    }

    public String netconfGetAlarms(String node) {
        reconnection(node);
        return netconfProtocolUtils.send("<get>\n" +
                "<filter type=\"subtree\">\n" +

                "<alarms xmlns=\"urn:ccsa:yang:acc-alarms\">\n" +

                "</alarms>\n" +

                "</filter>\n" +
                "</get>").toString();
    }


    public String netconfGetCurrentPerformances(String node, TcaParameter tcaParameter) {
        reconnection(node);
        String object = "";
        if (!tcaParameter.getPmParameterName().isEmpty())
            object += " <pm-parameter-name>" + tcaParameter.getPmParameterName() + "</pm-parameter-name>\n";
        if (!tcaParameter.getObjectName().isEmpty())
            object += " <object-name>" + tcaParameter.getObjectName() + "</object-name>\n";
        if (!tcaParameter.getStartTime().isEmpty())
            object += " <start-time>" + tcaParameter.getStartTime() + "</start-time>\n";
        if (!tcaParameter.getGranularity().isEmpty())
            object += " <granularity>" + tcaParameter.getGranularity() + "</granularity>\n";
        if (!tcaParameter.getObjetType().isEmpty())
            object += " <object-type>" + tcaParameter.getObjetType() + "</object-type>\n";

        System.out.println(object);

        return netconfProtocolUtils.send("<get>\n" +
                "<filter type=\"subtree\">\n" +

                "<performances xmlns=\"urn:ccsa:yang:acc-performance\">\n" +

                " <performance>\n" +

//                    "  <object-name>PTP=/shelf=1/slot=8/subslot=1/port=101</object-name>"+
                object +

                " </performance>\n" +

                "</performances>\n" +

                "</filter>\n" +
                "</get>").toString();
    }

}
